using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Events;
using UnityEngine.SceneManagement;

/// <summary>
/// 场景切换模块
/// </summary>
public class ScenesMgr : Singleton<ScenesMgr>
{
    /// <summary>
    /// 同步加载
    /// </summary>
    /// <param name="name"></param>
    public void LoadScene(string name, UnityAction fun)
    {
        SceneManager.LoadScene(name);
        //加载完成过后 执行fun
        fun();
    }

    /// <summary>
    /// 提供给外部的 异常加载的接口
    /// </summary>
    /// <param name="name"></param>
    /// <param name="fun"></param>
    public void LoadSceneAsync(string name, UnityAction fun)
    {
        MonoMgr.GetInstance().StartCoroutine(ReallyLoadSceneAsyn(name, fun));
    }

    /// <summary>
    /// 协程异步加载场景
    /// </summary>
    /// <param name="name"></param>
    /// <param name="fun"></param>
    /// <returns></returns>
    private IEnumerator ReallyLoadSceneAsyn(string name, UnityAction fun)
    {
        AsyncOperation asyncOp = SceneManager.LoadSceneAsync(name);
        //强制暂停场景激活​​,即使加载进度已达90%也不自动跳转场景。
        asyncOp.allowSceneActivation = false;
        //第一阶段:等待激活
        //返回场景加载进度(协程函数返回1个数字后,)
        while (asyncOp.progress < 0.9f)
        {
            //更新进度条
            UpdateProgress(asyncOp.progress);
            yield return asyncOp.progress;
        }
        //第二阶段:等待激活
        UpdateProgress(1.0f);   //强制显示100%
        asyncOp.allowSceneActivation = true;
        // 等待完全加载
        while (!asyncOp.isDone)
        {
            yield return null;
        }
        //确保场景初始化完成
        yield return new WaitForEndOfFrame();

        //加载完成后 执行fun
        fun?.Invoke();
    }

    private void UpdateProgress(float progress)
    {
        // 注意：实际进度范围是0-0.9，需要转换为0-1显示
        float displayProgress = Mathf.Clamp01(progress / 0.9f);
        ListenerMgr.GetInstance().Trigger("SceneProgress", displayProgress);
    }
}
